package edu.cornell.cubooks.validator;

import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;

import edu.cornell.cubooks.domain.Posting;
import edu.cornell.cubooks.utils.Santizer;

public class PostingValidator {
	
	private static final int MAX_DESC_LENGTH = 1000;
	
	public void validate(Posting posting, Errors errors) {
		
		posting.setDescription(Santizer.santize(posting.getDescription()));
		posting.setTitle(Santizer.santize(posting.getTitle()));
		
		if (!StringUtils.hasLength(posting.getTitle().trim())) {
			errors.rejectValue("title", "posting.required.field");
		}

		if (!StringUtils.hasLength(posting.getDescription().trim())) {
			errors.rejectValue("description", "posting.required.field");
		}
		
		if (posting.getDescription().trim().length() > MAX_DESC_LENGTH) {
			errors.rejectValue("description", "posting.description.toolong");
		}
		
		if (posting.getPrice() <= 0.0) {
			errors.rejectValue("price", "posting.price.invalid");
		}
	}
}
